# -*- coding: utf-8 -*-
'''
Created on Feb 28, 2013

@author: LONG HOANG GIANG
'''
from CrawlerLib2 import commonlib
from Model.storymodelv3 import StoryModel
import os
import re



PATH = '/longhoanggiang/data/500dck/toc.ncx'


class EPub():
    
    __path = ''
    __database = ''
    
    def __init__(self, path, database):
        if os.path.isdir(path): raise Exception, 'Input must be xml file (toc.ncx)'
        self.__path = path
        self.__database = database
        
    def getCategories(self):
        xml = commonlib.file_get_contents(self.__path)
        xml = re.sub(r"\<ncx xmlns=[^>]+\>", "<ncx>", xml)
        tree = commonlib.buildTreeFromXml(xml)
        folder = os.path.dirname(self.__path)
        data = []
        for navPoint in tree.xpath("//navPoint"):
            label = commonlib.stringify(navPoint.xpath("./navLabel/text")[0])
            content = navPoint.xpath("./content")[0]
            src = content.get('src', '')
            if src == '': continue
            src = os.path.join(folder, src)
            data.append({'title': label, 'url': src})
        return data
    
    def getDetail(self, url):
        content = commonlib.file_get_contents(url)
        return content
    
    def process(self):
        chapters = self.getCategories()
        smodel = StoryModel(self.__database)
        smodel.open(True)
        for chapter in chapters:
            filepath = re.sub(r"#chapter\d+", "", chapter['url'])
            title = commonlib.toUpper(chapter['title'])
            print title
            detail = self.getDetail(filepath).strip()
            if detail == '': raise
            smodel.add_story(title, detail, 0)
        smodel.close()
        
if __name__ == '__main__':
    
    pub = EPub(PATH, '/longhoanggiang/database/500dck')
    pub.process()
    
    print '> Finished !!!'